package jschool.util;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.media.Buffer;
import javax.media.CaptureDeviceInfo;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.VideoFormat;
import javax.media.util.BufferToImage;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.BevelBorder;

import jschool.persistencia.Conexion;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class CapturadorDeCamara extends JPanel implements ActionListener {

	private static final long serialVersionUID = 1L;
	public static Player reproductor = null;
	public CaptureDeviceInfo informadorDeCaptura = null;
	public MediaLocator rutaDispositivo = null;
	public JButton btnCaptura = null;
	public JButton btnPause = null;
	public Buffer buf = null;
	public Image img = null;
	public VideoFormat vf = null;
	public BufferToImage btoi = null;
	public Robot recorder;
	public boolean parar;
	public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH-mm-ss";
	public static String nombreImagen = null;
	public int count;

	public CapturadorDeCamara() {

		try {
			recorder = new Robot();

			setLayout(null);
			setBounds(new Rectangle(8, 2, 400, 400));
			setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
			btnCaptura = new JButton("Fotografiar");
			btnCaptura.setBounds(new Rectangle(2, 175, 172, 26));
			btnCaptura.addActionListener(this);
			try {

				rutaDispositivo = new MediaLocator("vfw://0");
				reproductor = Manager.createRealizedPlayer(rutaDispositivo);
				reproductor.start();
				Component comp;
				if ((comp = reproductor.getVisualComponent()) != null) {
					comp.setBounds(new Rectangle(2, 3, 400, 400));
					;
					add(comp);
				}
				add(btnCaptura);
			} catch (Exception e) {
				e.printStackTrace();
				Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE,
						null, e);
				JOptionPane.showMessageDialog(null,
						"No se encontro el Dispositivo de Video");
			}
		} catch (Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, "No se instancio el Recorder");
		}
	}

	public void paintComponent(Graphics g) {
		super.paintComponent(g);

		g.setColor(Color.black);
	}

	public static void playerclose() {
		reproductor.close();
		reproductor.deallocate();
	}

	public void actionPerformed(ActionEvent e) {
		JComponent c = (JComponent) e.getSource();
		parar = true;
		if (c == btnCaptura) {
			count = 0;
			while (parar) {

				Calendar cal = Calendar.getInstance();
				SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
				nombreImagen = sdf.format(cal.getTime());

				try {
					recorder.delay(2250);
				} catch (Exception a) {
				}
				count++;
				FrameGrabbingControl fgc = (FrameGrabbingControl) reproductor
						.getControl("javax.media.control.FrameGrabbingControl");
				buf = fgc.grabFrame();

				btoi = new BufferToImage((VideoFormat) buf.getFormat());
				img = btoi.createImage(buf);
				nombreImagen = JOptionPane.showInputDialog(null,
						"Ingrese nombre para almacenar la Imagen");
				if (nombreImagen.equalsIgnoreCase(null)) {
					JOptionPane.showMessageDialog(null,
							"Ingrese un nombre para la foto");
					parar = true;
				} else {
					saveJPG(img, ".\\imagenesEmpleados\\empleado_"
							+ nombreImagen + ".jpg");
					parar = true;
				}
				break;
			}
			destruirRobot();
			CapturadorDeCamara.this.setVisible(false);
			/* restaurarComponentes(null, null); */
			parar = true;
		}
	}

	public static void saveJPG(Image img, String s) {
		BufferedImage bi = new BufferedImage(img.getWidth(null), img
				.getHeight(null), BufferedImage.TYPE_INT_RGB);
		Graphics2D g2 = bi.createGraphics();
		g2.drawImage(img, null, null);

		FileOutputStream out = null;
		try {
			out = new FileOutputStream(s);
		} catch (java.io.FileNotFoundException io) {
			io.printStackTrace();
			Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null,
					io);
			JOptionPane.showMessageDialog(null,
					"Ruta de Almacenamiento no Encontrada");
		}
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
		param.setQuality(0.75f, true);
		encoder.setJPEGEncodeParam(param);

		try {
			encoder.encode(bi);
			out.close();
		} catch (java.io.IOException io) {
			io.printStackTrace();
			Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null,
					io);
			JOptionPane.showMessageDialog(null,
					"Error de Entrada/Salida de los Datos");
		}
	}

	public class pause extends Thread implements ActionListener {

		public pause() {
			run();
		}

		public void run() {

			while (true) {
			}

		}

		public void actionPerformed(ActionEvent e) {
			if (e.getSource() == btnPause)
				parar = false;
		}

	}

	public void restaurarComponentes(JButton boton, JPanel panel) {
		panel.setVisible(true);
		boton.setVisible(true);

	}

	public void destruirRobot() {
		reproductor.close();
	}
}
